package com.wstuo.common.config.dictionary.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.dictionary.dao.IDataDictionaryGroupDAO;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryItemsDAO;
import com.wstuo.common.config.dictionary.dto.DataDictionaryItemsDTO;
import com.wstuo.common.config.dictionary.dto.DataDictionaryQueryDTO;
import com.wstuo.common.config.dictionary.entity.DataDictionaryGroup;
import com.wstuo.common.config.dictionary.entity.DataDictionaryItems;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;

/**
 * 数据字典项业务类.
 * 
 * @author QXY
 */
public class DataDictionaryItemsService implements IDataDictionaryItemsService {

	@Autowired
	private IDataDictionaryItemsDAO dataDictionaryItemsDAO;
	@Autowired
	private IDataDictionaryGroupDAO dataDictionaryGroupDAO;
	private static final Logger LOGGER = Logger.getLogger( DataDictionaryItemsService.class );
	/**
	 * 保存数据字典
	 * 
	 * @param dto
	 */
	@Transactional
	public void saveDataDictionaryItems(DataDictionaryItemsDTO dto) {

		DataDictionaryItems entity = new DataDictionaryItems();
		dto2entity(dto, entity);

		if (dto.getGroupCode() != null) {// 根据Code查找
			DataDictionaryGroup group = dataDictionaryGroupDAO.findUniqueBy(
					"groupCode", dto.getGroupCode());
			entity.setDatadicGroup(group);
			// add mars
			if (group.getDatadicItems() == null) {
				List<DataDictionaryItems> datadicItems = new ArrayList<DataDictionaryItems>();
				group.setDatadicItems(datadicItems);
			}
			group.getDatadicItems().add(entity);
		}

		dataDictionaryItemsDAO.save(entity);

		dto.setDcode(entity.getDcode());
	}

	/**
	 * 删除数据字典
	 * 
	 * @param no 数据字典项编
	 */
	@Transactional
	public void removeDataDictionaryItems(Long no) {
		dataDictionaryItemsDAO.delete(dataDictionaryItemsDAO.findById(no));
	}

	/**
	 * 批量删除数据字典
	 * 
	 * @param nos 编号数组
	 */
	@Transactional
	public boolean removeDataDictionaryItemses(Long[] nos) {

		try {
			dataDictionaryItemsDAO.deleteByIds(nos);
		} catch (Exception ex) {
			throw new ApplicationException("ERROR_DATA_CAN_NOT_DELETE/n", ex);
		}
		return true;
	}

	/**
	 * 保存数据字典
	 * 
	 * @param dto
	 * @return DataDictionaryItemsDTO
	 */
	@Transactional
	public DataDictionaryItemsDTO mergeDataDictionaryItems(
			DataDictionaryItemsDTO dto) {
		DataDictionaryItems entity = dataDictionaryItemsDAO.findById(dto
				.getDcode());

		dto2entity(dto, entity);
		if (null != dto.getGroupNo()) {
			DataDictionaryGroup group = dataDictionaryGroupDAO.findById(dto
					.getGroupNo());
			entity.setDatadicGroup(group);
		}

		entity = dataDictionaryItemsDAO.merge(entity);

		entity2dto(entity, dto);

		return dto;
	}

	/**
	 * 保存数据字典
	 * 
	 * @param dto
	 */
	@Transactional
	public void updataDataDictionaryItems(DataDictionaryItemsDTO dto) {
		if (dto.getDcode() != null) {
			DataDictionaryItems entity = dataDictionaryItemsDAO.findById(dto
					.getDcode());

			if (dto.getDescription() == null) {
				dto.setDescription(entity.getDescription());
			}

			if (dto.getDflag() == null) {
				dto.setDflag(entity.getDflag());
			}

			if (dto.getDname() == null) {
				dto.setDname(entity.getDname());
			}

			if (dto.getGroupNo() == null) {
				dto.setGroupNo(entity.getDatadicGroup().getGroupNo());
			}

			if (dto.getRemark() == null) {
				dto.setRemark(entity.getRemark());
			}

			dto2entity(dto, entity);

			if (null != dto.getGroupNo()) {
				DataDictionaryGroup group = dataDictionaryGroupDAO.findById(dto
						.getGroupNo());

				entity.setDatadicGroup(group);
				dto.setGroupName(entity.getDatadicGroup().getGroupName());
			}

			dataDictionaryItemsDAO.update(entity);
		}
	}

	/**
	 * 批量修改数据字典
	 * 
	 * @param dtos 数据字典DTO集合
	 */
	@Transactional
	public void mergeAllDataDictionaryItem(List<DataDictionaryItemsDTO> dtos) {
		List<DataDictionaryItems> entities = new ArrayList<DataDictionaryItems>();

		for (DataDictionaryItemsDTO dto : dtos) {
			DataDictionaryItems entity = new DataDictionaryItems();
			dto2entity(dto, entity);
			if (null != dto.getGroupNo()) {
				DataDictionaryGroup group = dataDictionaryGroupDAO.findById(dto
						.getGroupNo());
				entity.setDatadicGroup(group);
				dto.setGroupName(entity.getDatadicGroup().getGroupName());
			}
			entities.add(entity);
		}

		dataDictionaryItemsDAO.mergeAll(entities);
	}

	/**
	 * 根据编号查找数据字典
	 * 
	 * @param no 数据字典编号
	 */
	public DataDictionaryItemsDTO findDataDictionaryItemById(Long no) {
		DataDictionaryItemsDTO dto = new DataDictionaryItemsDTO();
		DataDictionaryItems entity = dataDictionaryItemsDAO.findById(no);
		if (entity != null) {
			entity2dto(entity, dto);
		}
		return dto;
	}

	/**
	 * 根据数据字典分组名称查找数据字典
	 * 
	 * @param name 数据字典分组名称
	 * @return DataDictionaryItemsDTO
	 */
	public DataDictionaryItemsDTO findDataDictionaryItemByName(String name) {
		List<DataDictionaryItems> entities = dataDictionaryItemsDAO.findBy(
				"dname", name);
		DataDictionaryItemsDTO dto = null;
		for (DataDictionaryItems entity : entities) {
			dto = new DataDictionaryItemsDTO();
			entity2dto(entity, dto);
		}
		return dto;
	}

	/**
	 * 分页查询数据字典
	 * 
	 * @param dataDictionaryQueryDTO 查询DTO
	 * @param start 开始
	 * @param limit 每页数据条数
	 * @return PageDTO
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findDictionaryItemsByPage(
			DataDictionaryQueryDTO dataDictionaryQueryDTO, int start,
			int limit, String sidx, String sord) {

		PageDTO p = dataDictionaryItemsDAO.findPager(dataDictionaryQueryDTO,
				start, limit, sidx, sord);
		List<DataDictionaryItems> entities = p.getData();
		List<DataDictionaryItemsDTO> dtos = new ArrayList<DataDictionaryItemsDTO>(
				entities.size());

		for (DataDictionaryItems entity : entities) {
			DataDictionaryItemsDTO dto = new DataDictionaryItemsDTO();
			entity2dto(entity, dto);
			String groupCode = entity.getDatadicGroup().getGroupCode();
			// 分组编码
			if (entity.getDatadicGroup() != null&& groupCode != null) {
				dto.setGroupCode(groupCode);
			}
			dtos.add(dto);
		}

		p.setData(dtos);
		return p;
	}

	/**
	 * 根据数据字典分组编号查找对应项字典项列表
	 * 
	 * @param no 分组编号
	 * @return List<DataDictionaryItemsDTO> 字典项集
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public List<DataDictionaryItemsDTO> findDataDictionaryItemByGroupNo(Long no) {
		DataDictionaryGroup group = dataDictionaryGroupDAO.findById(no);
		List<DataDictionaryItems> entities = group.getDatadicItems();
		List<DataDictionaryItemsDTO> dtos = new ArrayList<DataDictionaryItemsDTO>();
		for (DataDictionaryItems entity : entities) {
			DataDictionaryItemsDTO dto = new DataDictionaryItemsDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		return dtos;
	}

	/**
	 * 根据数据字典Key查找集合.
	 * @param code
	 */
	@Transactional
	public List<DataDictionaryItemsDTO> findDictionaryItemByGroupCode(
			String code) {
		DataDictionaryGroup group = dataDictionaryGroupDAO.findUniqueBy(
				"groupCode", code);
		List<DataDictionaryItemsDTO> dtos = new ArrayList<DataDictionaryItemsDTO>();
		if (group != null) {
			List<DataDictionaryItems> entities = group.getDatadicItems();
			for (DataDictionaryItems entity : entities) {
				DataDictionaryItemsDTO dto = new DataDictionaryItemsDTO();
				entity2dto(entity, dto);
				dtos.add(dto);
			}
		}
		return dtos;

	}

	/**
	 * dto2entity
	 * @param dto
	 * @param entity
	 */
	private void dto2entity(DataDictionaryItemsDTO dto,
			DataDictionaryItems entity) {

		try {
			BeanUtils.copyProperties(entity, dto);
		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	/**
	 * entity2dto
	 * @param entity
	 * @param dto
	 */
	private void entity2dto(DataDictionaryItems entity,
			DataDictionaryItemsDTO dto) {
		if (entity != null && entity.getDatadicGroup() != null) {
			Long groupNo = entity.getDatadicGroup().getGroupNo();
			String groupName = entity.getDatadicGroup().getGroupName();

			dto.setGroupNo(groupNo);
			dto.setGroupName(groupName);
		}

		try {
			BeanUtils.copyProperties(dto, entity);
		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	/**
	 * 导出数据方法
	 * @param dataDictionaryQueryDTO
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked" })
	@Transactional
	public InputStream exportDataDictionaryItems(
			DataDictionaryQueryDTO dataDictionaryQueryDTO, int start,
			int limit, String sidx, String sord) {

		StringWriter sw = new StringWriter();

		CSVWriter csvw = new CSVWriter(sw);

		List<String[]> data = new ArrayList<String[]>();
		LanguageContent lc = LanguageContent.getInstance();
		data.add(new String[] { lc.getContent("label.role.roleName"),
				lc.getContent("label.role.roleDescription"),
				lc.getContent("label.role.roleMark") });

		PageDTO p = dataDictionaryItemsDAO.findPager(dataDictionaryQueryDTO,
				start, CSVWriter.EXPORT_SIZE, sidx, sord);

		if (p != null && p.getData() != null && p.getData().size() > 0) {
			List<DataDictionaryItems> entities = p.getData();
			for (DataDictionaryItems item : entities) {
				data.add(new String[] { item.getDname(), item.getDescription(),
						item.getRemark()
				});
			}
		}
		csvw.writeAll(data);
		
		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
        	if(csvw!=null){
        		csvw.flush();
    			csvw.close();
        	}
			if(sw!=null){
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;

	}

	/**
	 * 导入数据方法.
	 * 
	 * @param importCSVFile
	 * @return String
	 */
	@Transactional
	public String importDataDictionaryItems(File importCSVFile) {
		String result = "";
		int insert = 0;
		int update = 0;
		int total = 0;
		int failure = 0;
		Reader rd = null;
		CSVReader reader = null;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(importCSVFile);
			rd = new InputStreamReader(new FileInputStream(importCSVFile), fileEncode);// 以字节流方式读取数据
			reader = new CSVReader(rd);
			String[] line = null;
			try {
				while ((line = reader.readNext()) != null) {
					DataDictionaryItems dataDictionayItem = new DataDictionaryItems();
					dataDictionayItem.setDname(line[0].toString());
					dataDictionayItem.setDescription(line[1].toString());
					dataDictionayItem.setRemark(line[2].toString());
					if (StringUtils.hasText(line[3].toString())) {
						DataDictionaryGroup dataDictionaryGroup = dataDictionaryGroupDAO
								.findUniqueBy("groupCode", line[3].toString());
						if (dataDictionaryGroup != null) {
							dataDictionayItem
									.setDatadicGroup(dataDictionaryGroup);
						}
					}
					dataDictionayItem.setDno(line[4]);
					dataDictionayItem.setColor(line[5].toString());
					// 系统数据
					Byte dataFlag = 0;
					if (StringUtils.hasText(line[6].toString())&& line[6].toString().equals("1")) {
						dataFlag = 1;
					}
					dataDictionayItem.setDataFlag(dataFlag);
					dataDictionaryItemsDAO.merge(dataDictionayItem);
					insert++;
					total++;
				}

				result = "Total:" + total + ",&nbsp;Insert:" + insert
						+ ",&nbsp;Update:" + update + ",&nbsp;Failure:"
						+ failure;
			} catch (Exception e) {
				LOGGER.error("import DataDictionaryItems",e);
				result = "IOError";
			}
		} catch (Exception e1) {
			LOGGER.error("import DataDictionaryItems",e1);
			result = "FileNotFound";
		}finally{
			try {
				if(rd!=null){
					rd.close();
				}
				if(reader!=null){
					reader.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
		return result;
	}
	/**
	 *导入数据
	 */
	@Transactional
	public String importDataDictionaryItems(File importCSVFile, String code) {
		String result = "";
		int insert = 0;
		int update = 0;
		int total = 0;
		int failure = 0;
		Reader rd = null;
		CSVReader reader = null;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(importCSVFile);
			rd = new InputStreamReader(new FileInputStream(importCSVFile), fileEncode);// 以字节流方式读取数据
			reader = new CSVReader(rd);
			String[] line = null;
			try {
				while ((line = reader.readNext()) != null) {
					DataDictionaryItems dataDictionayItem = new DataDictionaryItems();
					dataDictionayItem.setDname(line[0].toString());
					dataDictionayItem.setDescription(line[1].toString());
					dataDictionayItem.setRemark(line[2].toString());
					if (!StringUtils.hasText(code)) {// 不為空時是指用户自己导入，为空是系统加载数据时
						code = line[3].toString();
						dataDictionayItem.setDno(line[4]);
						dataDictionayItem.setColor(line[5].toString());
						// 系统数据
						Byte dataFlag = 0;
						if (StringUtils.hasText(line[6].toString())
								&& line[6].toString().equals("1")) {
							dataFlag = 1;
						}
						dataDictionayItem.setDataFlag(dataFlag);
					}
					DataDictionaryGroup dataDictionaryGroup = dataDictionaryGroupDAO
							.findUniqueBy("groupCode", code);
					if (dataDictionaryGroup != null) {
						dataDictionayItem.setDatadicGroup(dataDictionaryGroup);
					}
					dataDictionaryItemsDAO.merge(dataDictionayItem);
					insert++;
					total++;
				}

				result = "Total:" + total + ",&nbsp;Insert:" + insert
						+ ",&nbsp;Update:" + update + ",&nbsp;Failure:"
						+ failure;
			} catch (Exception e) {
				LOGGER.error("import DataDictionaryItems",e);
				result = "IOError";
			}
		} catch (Exception e1) {
			LOGGER.error("import DataDictionaryItems",e1);
			result = "FileNotFound";
		} finally {
			try {
				if(rd!=null){
					rd.close();
				}
				if(reader!=null){
					reader.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
		return result;
	}

    /**
     * 根据编号查询数据字典信息
     * @param no
     * @return DataDictionaryItemsDTO
     */
	public DataDictionaryItemsDTO findByDcode(Long no) {
		DataDictionaryItems entity = dataDictionaryItemsDAO.findUniqueBy(
				"dcode", no);
		DataDictionaryItemsDTO dto = new DataDictionaryItemsDTO();
		entity2dto(entity, dto);
		return dto;
	}
	
	/**
	 *根据编号查找是否为系统数据
	 */
	public int findByDcodeIsSystemData(Long[] nos) {
		List<DataDictionaryItems> data=dataDictionaryItemsDAO.findByIds(nos);
		int result =0;
		if(data!=null && data.size()>0){
			for (int i = 0; i < data.size(); i++) {
				if(data.get(i)!=null && data.get(i).getDno()!=null && (data.get(i).getDataFlag()==1 || data.get(i).getDno().equals("task_workforce")||data.get(i).getDno().equals("task_personal"))){
					result=1;
					break;
				}
			}
		}
		return result;
	}

}
